package com.neihanduanzi.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.neihanduanzi.BaseActivity;
import com.neihanduanzi.R;
import com.neihanduanzi.adapter.VideoListAdapter;
import com.neihanduanzi.api.VideoService;
import com.neihanduanzi.database.DButil;
import com.neihanduanzi.database.VideoDb;
import com.neihanduanzi.model.VideoModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class ZVideoFragment extends BaseFragment implements AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = "ZVideoFragment";
    private VideoService mVideoService;
    private ListView mListView;
    private List<VideoModel.Fdata> mDataBeanList;
    private VideoListAdapter mAdapter;
    private SwipeRefreshLayout mRefreshLayout;


    public ZVideoFragment() {
        // Required empty public constructor
    }

    @Override
    public String getFragmentTitle() {
        return "视频";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View ret = inflater.inflate(R.layout.fragment_zvideo, container, false);
        mListView = (ListView) ret.findViewById(R.id.Video_list);
        mListView.setAdapter(mAdapter);
        initDatabase();
        initData();
        mRefreshLayout = ((SwipeRefreshLayout) ret.findViewById(R.id.recommend_refresh));
        mRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.pink));
        mRefreshLayout.setOnRefreshListener(this);
        mListView.setOnItemClickListener(this);
        return ret;
    }

    private void initDatabase() {
        List<VideoDb> videoDbs = DButil.queryAllVideo();
        if (videoDbs != null) {
            String group = videoDbs.get(0).getGroup();
            load(group);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataBeanList=new ArrayList<>();
        mAdapter = new VideoListAdapter(getContext(),mDataBeanList);
    }

    private void initData() {
            Retrofit.Builder builder = new Retrofit.Builder();
            builder.baseUrl("http://ic.snssdk.com/neihan/stream/mix/");
            builder.addConverterFactory(ScalarsConverterFactory.create());
            Retrofit retrofit = builder.build();
            mVideoService = retrofit.create(VideoService.class);
            Call<String> call = mVideoService.FirstRequst();
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if (response.isSuccessful()) {
                    mRefreshLayout.setRefreshing(false);
                    String total = response.body();
                    Log.d(TAG, "onResponse: " + total);
                    load(total);
                    if (total != null) {
                        DButil.deleteVideo();
                        VideoDb videoDb = new VideoDb();
                        videoDb.setGroup(total);
                        DButil.addData(videoDb);
                    }
                }}
                @Override
                public void onFailure(Call<String> call, Throwable t) {
//                    Toast.makeText(getContext(), "网络不太好哦", Toast.LENGTH_SHORT).show();
                }
            });
        
    }

    private void load(String total) {
        try {
            JSONObject Jtatal = new JSONObject(total);
            JSONObject Fdata = Jtatal.getJSONObject("data");
            String s = Fdata.toString();
            Gson gson = new Gson();
            VideoModel model = gson.fromJson(s, VideoModel.class);

            mDataBeanList.addAll(model.getFdatas());
            mAdapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        VideoModel.Fdata.VideoDetial fdata = mDataBeanList.get(position).getVideoDetial();
        Gson gson = new Gson();
        String s = gson.toJson(fdata);
        Intent intent = new Intent(getContext(), BaseActivity.class);
        intent.putExtra("Data",s);
        intent.putExtra("type",2);
        intent.putExtra("group_id",fdata.getGroup_id());
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        initData();
    }
}
